
package com.yimixian.app.activity;

import com.baidu.mapapi.SDKInitializer;
import com.crashlytics.android.Crashlytics;
import com.igexin.sdk.PushManager;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.onlineconfig.OnlineConfigAgent;
import com.umeng.update.UmengUpdateAgent;
import com.yimixian.app.BuildConfig;
import com.yimixian.app.EventBusDomain.OrderListPointTab;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.YMXApplication;
import com.yimixian.app.cart.CartDetailActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.fragment.CategoryFragment;
import com.yimixian.app.fragment.HomeFragment;
import com.yimixian.app.fragment.MyFragment;
import com.yimixian.app.fragment.OrderFragmentGroup;
import com.yimixian.app.fragment.OrderMvpFragment;
import com.yimixian.app.fragment.SessionActivityFragment;
import com.yimixian.app.fragment.SessionActivityListFragment;
import com.yimixian.app.goods.GoodDetailTopFragment;
import com.yimixian.app.receiver.GeTuiPushReceiver;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.user.UserRegistrationActivity;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.animator.LayerEnableAnimatorListenerAdapter;
import com.ymx.sdk.animator.animatorUtils;

import de.greenrobot.event.EventBus;
import io.fabric.sdk.android.Fabric;
import rx.functions.Action1;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class YMXMainActivity extends BaseNaviFragmentGroupActivity
        implements OnClickListener, View.OnTouchListener {
    public static final String TAB_INDEX_KEY = "tab_index_key";
    public static final String SECTION_KEY = "section_key";
    public static final int TAB_KIND = R.id.rb_tab_kind;
    public static final int TAB_HOME = R.id.rb_tab_home;
    // public static final int TAB_CART = R.id.rb_tab_cart;
    public static final int TAB_ORDER = R.id.rb_tab_order;
    public static final int TAB_MINE = R.id.rb_tab_mine;
    public static final String INTENT_EXTRA_EXIT = "exit";
    public static final String HOME_STATE_KEY = "home_state";
    public static final String HOME_DATA_KEY = "home_data";
    public static final String SESSION_ACTIVITY_ID = "session_activity_id";
    //判断各种第一次
    public static boolean IS_FIRST_GET_HOT_TIPS = true;
    private  String mSessionActivityId ="";
    public boolean isHomeFlush;
    private int mTabIndex;
    // private RadioGroup mTab;
    private TextView mKindTab;
    // public TextView mCartTab;
    private TextView mOrderTab;
    private TextView mMineTab;
    private TextView mHomeTab;
    public TextView mCartTotalQuantity;
    private TextView orderPoint;
    public TextView boundPoint;
    private long mOldBackPressTime;
    private DataManager mDataManager;
    private YmxDataService mYmxDataService;
    private SharedPreferences mSharedPreferences;
    private FrameLayout mActivityLayout;
    private FrameLayout mBottomBar;
    private FrameLayout mMaskLayout;
    public TextView mCartContent;
    private ImageView mCartView;
    private ImageView mCartDetailView;
    private ImageView mCartDetailViewHide;
    public TextView mCartDetailContent;
    private FrameLayout mCartLayout;
    private FrameLayout mCartDetailLayout;
    public FrameLayout mGuideLayout;
    private ImageView mAddressGuideView;
    private ImageView mKindGuideView;
    private ImageView mSearchGuideView;
    private boolean mIsBackAnimating = false;
    public boolean mIsHome = true;

    public static final int SAVED_STORE_TYPE_ADDRESS = 0;
    public static final int SAVED_STORE_TYPE_PICK_UP = 1;
    private int mLastCheckTab = TAB_HOME;
    private String mSectionId = "";
    private static final long currentAnimDuration = 100;
    private static final long halfCurrentAnimDuration = currentAnimDuration / 2;

    private static final long halfCurrentAnimDuration2 = 0;
    public SessionActivityFragment mSessionFragment;
    boolean mIsFirst=true;
    private boolean isRefresh=false;
    private String mCityName="";
    public static boolean needChooseKindTab = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ymx_main);
        //刷新时间重置
        if (UiUtils.timeMap != null) UiUtils.timeMap.clear();
        setupSdks();
        setupMemberVariables();
        registerPushToken();
        mIsFirst=true;
         if (savedInstanceState == null) {
            mTabIndex = TAB_HOME;
        } else {
            mTabIndex = savedInstanceState.getInt(TAB_INDEX_KEY, TAB_HOME);
            mIsHome = savedInstanceState.getBoolean(HOME_STATE_KEY);
            mSessionActivityId=savedInstanceState.getString(SESSION_ACTIVITY_ID,"");
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initViews(mTabIndex);
        showGuideView();
        if (!mIsHome&&!TextUtils.isEmpty(mSessionActivityId))
        {
            mIsHome=true;
          //mCartLayout.setVisibility(View.INVISIBLE);
          //mBottomBar.setVisibility(View.INVISIBLE);
          //showActivityUI(mSessionActivityId);
        }
        dealTransmittedMessage();
    }

    private void dealTransmittedMessage() {
        Intent intent = getIntent();
        if(intent != null) {
            int type = intent.getIntExtra(GeTuiPushReceiver.TRANSMITTED_MESSAGE_TYPE,-1);
            if(GeTuiPushReceiver.TRANSMITTED_MESSAGE_TYPE_URL == type) {
                String url = intent.getStringExtra(GeTuiPushReceiver.TRANSMITTED_MESSAGE_EXTRA);
                if(!TextUtils.isEmpty(url)) {
                    Intent intent1 = new Intent(this, WebViewActivity.class);
                    intent1.putExtra(WebViewActivity.EXTRA_URL, url);
                    startActivity(intent1);
                }
            }
        }
    }

    public void showGuideView() {
        if (!SharedPreferencesHelper.getGuideHome()) {
            mGuideLayout.setVisibility(View.VISIBLE);
            if (mKindGuideView.getVisibility() != View.VISIBLE) {
                mKindGuideView.setVisibility(View.VISIBLE);
            }
        }
    }

    public void GuideViewChange() {         
        if (!SharedPreferencesHelper.getGuide2_1_0()) {
            //2.1
            if (showCategory())
                return;
            if (showSearch())
                return;
            if (showAddress())
                return;   
        } 
    }
    
    public boolean showCategory(){
        if (!SharedPreferencesHelper.getGuideHome()) {
            if (mKindGuideView.getVisibility() == View.VISIBLE) {
                mKindGuideView.setVisibility(View.GONE);
                mSearchGuideView.setVisibility(View.VISIBLE);
                SharedPreferencesHelper.setGuideHome(true);
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
    public boolean showSearch(){
        if (mSearchGuideView.getVisibility() == View.VISIBLE) {
            mSearchGuideView.setVisibility(View.GONE);
            mAddressGuideView.setVisibility(View.VISIBLE);
            SharedPreferencesHelper.setGuideSearch(true);
            return true;
         }else {
            return false;
        }
    }
    public boolean showAddress(){
        if (mAddressGuideView.getVisibility() == View.VISIBLE) {
            mKindGuideView.setVisibility(View.GONE);
            mAddressGuideView.setVisibility(View.GONE);
            mGuideLayout.setVisibility(View.GONE);
            SharedPreferencesHelper.setGuideAddress(true);
            SharedPreferencesHelper.setGuide2_1_0(true);
            HomeFragment homeFragment = (HomeFragment) getFragment(TAB_HOME);
            if (homeFragment != null){
                homeFragment.showHomeAd(true);
            }
            return true;
        }else {
            return false;
        }
    }
    

    private void initViews(int tabIndex) {
        mHomeTab = (TextView) findViewById(R.id.rb_tab_home);
        mKindTab = (TextView) findViewById(R.id.rb_tab_kind);
        mOrderTab = (TextView) findViewById(R.id.rb_tab_order);
        mMineTab = (TextView) findViewById(R.id.rb_tab_mine);
        mCartTotalQuantity = (TextView) findViewById(R.id.badge_number);
        orderPoint = (TextView) findViewById(R.id.order_point);
        boundPoint = (TextView) findViewById(R.id.bound_point);
        mActivityLayout = (FrameLayout) findViewById(R.id.fragment_stub_actvity);
        mBottomBar = (FrameLayout) findViewById(R.id.fl_tab_bar);
        mCartView = (ImageView) findViewById(R.id.iv_cart);
        mCartDetailView = (ImageView) findViewById(R.id.iv_detail_cart);
        mCartDetailViewHide = (ImageView) findViewById(R.id.iv_detail_cart_hide);
        mCartContent = (TextView) findViewById(R.id.cart_contnent);
        mCartDetailContent = (TextView) findViewById(R.id.cart_detail_contnent);
        mMaskLayout = (FrameLayout) findViewById(R.id.fl_mask);
        mCartLayout = (FrameLayout) findViewById(R.id.fl_cart);
        mCartDetailLayout = (FrameLayout) findViewById(R.id.fl_detail_cart);
        mGuideLayout = (FrameLayout) findViewById(R.id.fl_guide);
        mKindGuideView = (ImageView) findViewById(R.id.iv_guide_kind);
        mSearchGuideView = (ImageView) findViewById(R.id.iv_guide_search);
        mAddressGuideView = (ImageView) findViewById(R.id.iv_guide_address);
        mCartDetailView.setOnClickListener(this);
        mCartView.setOnClickListener(this);
        mGuideLayout.setOnClickListener(this);
        setTabClickListener();
        onCheckedChanged(tabIndex);
        CartManager.getInstance().setCartPriceData(mCartContent);
    }

    //param isSession:是否是活动会场来的
    public void initCartViewAnim(boolean isSession){
        if(!isSession){
//            UiUtils.showScaleAnimation(mCartView,1f,1.5f,1f,1.5f,300,false,null);
            UiUtils.showScaleAnimation(mCartView);
        }else{
//            UiUtils.showScaleAnimation(mCartDetailViewHide,1f,1.5f,1f,1.5f,300,false,null);
            UiUtils.showScaleAnimation(mCartDetailViewHide);
        }
    }

    public void setTabClickListener() {
//        mHomeTab.setOnClickListener(this);
//        mKindTab.setOnClickListener(this);
//        mOrderTab.setOnClickListener(this);
//        mMineTab.setOnClickListener(this);
        mHomeTab.setOnTouchListener(this);
        mKindTab.setOnTouchListener(this);
        mOrderTab.setOnTouchListener(this);
        mMineTab.setOnTouchListener(this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        saveCartViewLocation();
    }

    private void saveCartViewLocation() {
        if (SharedPreferencesHelper.getCartViewLocation() != null) {
            Point point = SharedPreferencesHelper.getCartViewLocation();
            if (0 == point.x && 0 == point.y) {
                getCartViewPosition();
            }
        }
    }

    private void getCartViewPosition() {
        int[] location = new int[2];
        if (mCartView != null) {
            mCartView.getLocationInWindow(location);
        }
        SharedPreferencesHelper.saveCartViewLocation(new Point(location[0], location[1]));
    }

    public void onCheckedChanged(int checkedId) {
        if (UiUtils.isFastDoubleClick()) {
            return;
        }
        switchTab(checkedId);
        mLastCheckTab = checkedId;
    }

    public void setDefaultColor() {
        mHomeTab.setTextColor(getResources().getColor(R.color.tab_default));
        mKindTab.setTextColor(getResources().getColor(R.color.tab_default));
        mOrderTab.setTextColor(getResources().getColor(R.color.tab_default));
        mMineTab.setTextColor(getResources().getColor(R.color.tab_default));
    }

    public void setDefaultDrawable() {
        mHomeTab.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home_home_icon, 0, 0);
        mKindTab.setCompoundDrawablesWithIntrinsicBounds(0,
                R.drawable.ic_home_kind, 0, 0);
        mOrderTab.setCompoundDrawablesWithIntrinsicBounds(0,
                R.drawable.home_order_icon, 0, 0);
        mMineTab.setCompoundDrawablesWithIntrinsicBounds(0,
                R.drawable.home_account_icon, 0, 0);

    }

    private void startClickAnimation(final View view){
        ScaleAnimation first = new ScaleAnimation(
                1.0f, 0.8f, 1.0f, 0.8f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        first.setDuration(100);
        first.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                ScaleAnimation second = new ScaleAnimation(
                        0.8f, 1.2f, 0.8f, 1.2f,
                        Animation.RELATIVE_TO_SELF, 0.5f,
                        Animation.RELATIVE_TO_SELF, 0.5f);
                second.setDuration(150);
                second.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        ScaleAnimation third = new ScaleAnimation(
                                1.2f, 1.0f, 1.2f, 1.0f,
                                Animation.RELATIVE_TO_SELF, 0.5f,
                                Animation.RELATIVE_TO_SELF, 0.5f);
                        third.setDuration(200);
                        view.startAnimation(third);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                view.startAnimation(second);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        view.startAnimation(first);
    }

    public void switchTab(int index) {
        setDefaultColor();
        setDefaultDrawable();
        switch (index) {
            case TAB_KIND:
                mKindTab.setTextColor(getResources().getColor(R.color.tab_check));
                mKindTab.setCompoundDrawablesWithIntrinsicBounds(0,
                        R.drawable.ic_home_kind_p, 0, 0);

                break;
            case TAB_HOME:
                mHomeTab.setTextColor(getResources().getColor(R.color.tab_check));
                mHomeTab.setCompoundDrawablesWithIntrinsicBounds(0,
                        R.drawable.home_home_icon_p, 0, 0);

                break;
            case TAB_ORDER:
                mOrderTab.setTextColor(getResources()
                        .getColor(R.color.tab_check));
                mOrderTab.setCompoundDrawablesWithIntrinsicBounds(0,
                        R.drawable.home_order_icon_p, 0, 0);
                break;
            case TAB_MINE:
                mMineTab
                        .setTextColor(getResources().getColor(R.color.tab_check));
                mMineTab.setCompoundDrawablesWithIntrinsicBounds(0,
                        R.drawable.home_account_icon_p, 0, 0);
                break;
        }
        if (!isRefresh){
            if (!mIsFirst&&mTabIndex==index)   {
                return;
            }
        }
        if (index == TAB_HOME){
            if (TextUtils.isEmpty(mCityName)){
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                    UMengConstants.NEW_HOME_PV);
            }else {
                HashMap<String, String> map = new HashMap<>();
                map.put("city", mCityName);
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                    UMengConstants.NEW_HOME_PV, map);
            }
        }
        if (index == TAB_MINE){
            DateUtil.setCityUMeng(null, UMengConstants.NEW_USERCENTER_PV);
        }
         switchPrimaryFragment(index);  
         mTabIndex = index;
         mIsFirst=false;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            switch (v.getId()) {
                case R.id.rb_tab_kind:
                    startClickAnimation(mKindTab);
                    onCheckedChanged(TAB_KIND);
                    break;
                case R.id.rb_tab_home:
                    startClickAnimation(mHomeTab);
                    onCheckedChanged(TAB_HOME);
                    break;
                case R.id.rb_tab_mine:
                    startClickAnimation(mMineTab);
                    onCheckedChanged(TAB_MINE);
                    break;
                case R.id.rb_tab_order:
                    startClickAnimation(mOrderTab);
                    onCheckedChanged(TAB_ORDER);
                    break;
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_guide:
                GuideViewChange();
                break;
            case R.id.title_bar_right_text:
                break;
//            case R.id.rb_tab_kind:
//                onCheckedChanged(TAB_KIND);
//                startClickAnimation(mKindTab);
//                break;
//            case R.id.rb_tab_home:
//                onCheckedChanged(TAB_HOME);
//                startClickAnimation(mHomeTab);
//                break;
//            case R.id.rb_tab_mine:
//                onCheckedChanged(TAB_MINE);
//                startClickAnimation(mMineTab);
//                break;
//            case R.id.rb_tab_order:
//                onCheckedChanged(TAB_ORDER);
//                startClickAnimation(mOrderTab);
//                break;
            case R.id.iv_cart:
                if(mCurrentPrimaryFragment != null && mCurrentPrimaryFragment instanceof CategoryFragment) {
                    MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                        UMengConstants.NEW_CATEGORY_CARTBTN);
                }
                if (mCurrentPrimaryFragment != null && mCurrentPrimaryFragment instanceof HomeFragment){
                    MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                            UMengConstants.NEW_HOME_CARTBTN);
                }
                if (userLogin()) return;
                if(!UiUtils.isFastDoubleClick()) {
                    DateUtil.setCityUMeng(null, UMengConstants.NEW_BOTTOM_CARTBTN);
                    startActivityForResult(CartDetailActivity.buildIntent(this), 0);
                    overridePendingTransition(R.anim.slide_in_from_bottom, 0);
                }
                break;
            case R.id.iv_detail_cart:
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                        UMengConstants.NEW_SESSION_CARTBTN);
                if (userLogin()) return;
                DateUtil.setCityUMeng(null, UMengConstants.NEW_BOTTOM_CARTBTN);
                startActivityForResult(CartDetailActivity.buildIntent(this), 0);
                overridePendingTransition(R.anim.slide_in_from_bottom, 0);
                break;
            default:
                break;
        }
    }

    private boolean userLogin() {
        if (DataManager.getInstance().get(CacheKeys.TOKEN) == null) {
            Intent intent = new Intent(this, UserRegistrationActivity.class);
            startActivityForResult(intent, Constants.CART_REGIST_REQUEST_CODE);
            overridePendingTransition(R.anim.slide_in_from_bottom, 0);
            return true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(needChooseKindTab){
            switchTab(YMXMainActivity.TAB_KIND);
            hideActivityUI();
            needChooseKindTab = false;
        }
        //订单项刷新
        if(mTabIndex == TAB_ORDER){
            OrderFragmentGroup group = (OrderFragmentGroup) getFragment(TAB_ORDER);
            List<Fragment> fragments = group.getChildFragmentManager().getFragments();
            for(Fragment fragment : fragments){
                if(fragment instanceof OrderMvpFragment){
                    OrderMvpFragment page = (OrderMvpFragment) fragment;
//                    if(!Strings.isNullOrEmpty(OrderMvpFragment.CHANG_FLAG)){
//                        String[] split = OrderMvpFragment.CHANG_FLAG.split(",");
//                        if(split.length == 2 && !"-1".equals(split[0])){
//                            page.initPresenter(Integer.parseInt(split[0]), split[1]);
//                        }else{
//                            page.initPresenter();
//                        }
//                    }else{
                        page.initPresenter();
//                    }
                    OrderMvpFragment.CHANG_FLAG = "";
                }
            }
        }
    }

    @Override
    protected void initPrimaryFragment() {
        onCheckedChanged(mLastCheckTab);
    }

    @Override
    protected Class<? extends Fragment> getPrimaryFragmentClass(int fragmentId) {
        Class<? extends Fragment> clazz = null;
        switch (fragmentId) {
            case TAB_HOME:
                clazz = HomeFragment.class;
                break;
            case TAB_KIND:
                clazz = CategoryFragment.class;
                break;
            case TAB_ORDER:
                clazz = OrderFragmentGroup.class;
                break;
            case TAB_MINE:
                clazz = MyFragment.class;
                break;

            default:
                clazz = CategoryFragment.class;
        }
        return clazz;
    }

    @Override
    protected Bundle getPrimaryFragmentArguments(int fragmentId) {
        return null;
    }

    @Override
    protected int getPrimaryFragmentStubId(int fragmentId) {
        return R.id.fragment_stub;
    }

    public static Intent buildIntent(Context context) {
        Intent intent = new Intent(context, YMXMainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        return intent;
    }

    public static Intent buildIntentTab(Context context, int tab) {
        Intent intent = new Intent(context, YMXMainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(TAB_INDEX_KEY, tab);
        return intent;
    }

    public static Intent buildIntentHomeTabSection(Context context, String sectionId) {
        Intent intent = new Intent(context, YMXMainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(TAB_INDEX_KEY, TAB_HOME);
        intent.putExtra(SECTION_KEY, sectionId);
        return intent;
    }

    public static Intent buildIntentSessionActivity(Context context, String sectionId) {
        Intent intent = new Intent(context, YMXMainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(HOME_STATE_KEY, false);
        intent.putExtra(HOME_DATA_KEY, sectionId);
        return intent;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if(Constants.CART_REGIST_REQUEST_CODE == requestCode) {
                //从购物车跳转到登陆页面 登陆完成跳转到购物车页面
                isRefresh=true;
                startActivityForResult(CartDetailActivity.buildIntent(this), 0);
                overridePendingTransition(R.anim.slide_in_from_bottom, 0);
                isRefresh=false;
            } else {
                isRefresh = true;
                switchTab(mTabIndex);
                isRefresh = false;
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (mIsHome&&!intent.getBooleanExtra(HOME_STATE_KEY, true)) {
            mSessionActivityId=intent.getStringExtra(HOME_DATA_KEY);
            showActivityUI(mSessionActivityId);
        }
        if (intent.getBooleanExtra(INTENT_EXTRA_EXIT, false)) {
            finish();
        }
        if (intent.getIntExtra(TAB_INDEX_KEY, -1) == TAB_HOME) {
            if (!mIsHome){
                hideActivityUI();
            }
            onCheckedChanged(TAB_HOME);
            mSectionId = intent.getStringExtra(SECTION_KEY);
        }else if (intent.getIntExtra(TAB_INDEX_KEY, -1) == TAB_KIND){
            onCheckedChanged(TAB_KIND);
        }
    }

    public static final Intent buildExitIntent(Context context, boolean exit) {
        Intent intent = new Intent(context, YMXMainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(TAB_INDEX_KEY, TAB_HOME);
        intent.putExtra(INTENT_EXTRA_EXIT, exit);
        return intent;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!mIsHome) {
                if (mIsBackAnimating) {
                    return true;
                }
                hideActivityUI();
                return true;
            }
            long diff = System.currentTimeMillis() - mOldBackPressTime;
            if (diff > Constants.APP_BACK_WAIT_DEFAULT_TIME) {
                mOldBackPressTime = System.currentTimeMillis();
                UiUtils.showToast(this, getString(R.string.press_exit_ymx));
            } else {
                mOldBackPressTime = 0;
                YMXApplication.getInstance().stopAppService();
                finish();
            }
            return true;
        } else {
            mOldBackPressTime = 0;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void setupSdks() {
        UmengUpdateAgent.update(this);
        Fabric.with(this, new Crashlytics());
        MobclickAgent.enableEncrypt(true);
        MobclickAgent.setDebugMode(false);
        OnlineConfigAgent.getInstance().updateOnlineConfig(this);
        PushManager.getInstance().initialize(getApplicationContext());
        SDKInitializer.initialize(getApplicationContext());
        if (BuildConfig.SERVER_ENVIRONMENT != Constants.ServerEnvironment.Release) {
            MobclickAgent.setCatchUncaughtExceptions(false);
        }
    }

    private void registerPushToken() {
        String clientId = PushManager.getInstance().getClientid(getApplicationContext());
        String token = mDataManager.get(CacheKeys.TOKEN);
        if (Strings.isNullOrEmpty(clientId) || Strings.isNullOrEmpty(token)) {
            return;
        }

        mYmxDataService
                .registerPushToken(clientId, token)
                .subscribe(
                        new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                            }
                        }
                );
    }

    private void setupMemberVariables() {
        mDataManager = DataManager.getInstance();
        // 这行代码的顺序不能被改变，只能放在这里，因为YmxRestService要用到这里。这是一个不好的设计！！
        try {
            String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            String installChannel = getPackageManager()
                    .getApplicationInfo(
                            getPackageName(), PackageManager.GET_META_DATA)
                    .metaData
                            .getString("UMENG_CHANNEL");
            mDataManager.put(CacheKeys.VERSION_NAME, versionName);
            mDataManager.put(CacheKeys.VERSION_CODE, versionCode);
            mDataManager.put(CacheKeys.INSTALL_CHANNEL, installChannel);
        } catch (PackageManager.NameNotFoundException ignored) {
        }

        mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFS_NAME, Context.MODE_PRIVATE);
        mDataManager.onMainActivityCreate(mSharedPreferences);
        mYmxDataService = YmxDataService.getInstance();
    }

    @Override
    public void onReiveServiceNotice(String action) {
        super.onReiveServiceNotice(action);
        if (Constants.ServicePageType.HOMEFRAGMENT.equals(action)) {
            HomeFragment homeFragment = (HomeFragment) getFragment(TAB_HOME);
            if (homeFragment != null) homeFragment.isNeedUpdate();
        }
        if (action.contains(Constants.ServicePageType.SESSIONFRAGMENT)){
            if (mSessionFragment != null) mSessionFragment.isNeedUpdate();
        }
        if (action.contains(Constants.ServicePageType.CATEGORYFRAGMENT)){
            CategoryFragment categoryFragment = (CategoryFragment) getFragment(TAB_KIND);
            if (categoryFragment != null) categoryFragment.isNeedUpdate();
        }
    }

    @Override
    public void onDestroy() {
        if(mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        mDataManager.onMainActivityDestroy(mSharedPreferences);
        EventBus.getDefault().unregister(this);// 反注册EventBus
        YMXApplication.getInstance().stopAppService();
        super.onDestroy();
    }

    public void setHomeTab() {
        onCheckedChanged(TAB_HOME);
    }

    public void onEventMainThread(OrderListPointTab event) {
        int number = event.getNumber();
        if (orderPoint == null || StringUtils.isEmpty(event.getType()))
            return;
        if (event.getType().equals(Constants.RedPointType.ORDER)){
            if (number > 0) {
                orderPoint.setVisibility(View.VISIBLE);
            } else {
                orderPoint.setVisibility(View.GONE);
            }
        }else if(event.getType().equals(Constants.RedPointType.BOUNS)){
            if (number > 0) {
                boundPoint.setVisibility(View.VISIBLE);
                //优惠券红点我的页面显示
                MyFragment myFragment = (MyFragment)getFragment(TAB_MINE);
                if (myFragment != null){
                    myFragment.showBonusRedPoint(true);
                }

            } else {
                if (event.getIsFeatch()){
                    //优惠券红点清除
                    HomeFragment homeNewFragment = (HomeFragment)getFragment(TAB_HOME);
                    if (homeNewFragment != null){
                        homeNewFragment.clearBonusRedPoint();
                    }
                }
                //优惠券红点我的页面显示
                MyFragment myFragment = (MyFragment)getFragment(TAB_MINE);
                if (myFragment != null){
                    myFragment.showBonusRedPoint(false);
                }
                boundPoint.setVisibility(View.GONE);
            }
        }

    }

    public void onEventMainThread(String message) {
        if(message != null) {
            // Gone掉购物车旁边的description
            if (Constants.EVENT_BUS_UPDATE_DESCRIPTION.equals(message)) {
                UiUtils.updateCartDescription(this, Constants.PageType.HOME);
                UiUtils.updateCartDescription(this, Constants.PageType.CATEGORY);
                EventBus.getDefault().removeStickyEvent(message);
            }
            if (Constants.CART_TOTAL_PRICE_CHANGE_BROADCAST.equals(message)){
                String str = CartManager.getInstance().getFormatTotalPrice();
                if(!StringUtils.isEmpty(str)){
                    mCartContent.setText(str);
                    mCartContent.setVisibility(View.VISIBLE);
                }else{
                    mCartContent.setVisibility(View.GONE);
                }
            }
        }
    }

    // 地址管理页面 监听到地址改变更新首页内容
    public void onEventMainThread(ShowAdSelectChange event) {
        clearServiceMapData(null);
        YMXMainActivity.IS_FIRST_GET_HOT_TIPS = true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(TAB_INDEX_KEY, mTabIndex);
        outState.putBoolean(HOME_STATE_KEY, mIsHome);
        outState.putString(SESSION_ACTIVITY_ID, mSessionActivityId);
        super.onSaveInstanceState(outState);
    }
    public void addSessionFragment(final String id){
        if (mHandler != null) mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                if (mSessionFragment == null) {
                    mSessionFragment = new SessionActivityFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString(HOME_DATA_KEY, id);
                    mSessionFragment.setArguments(bundle);
                }
                transaction.add(R.id.fragment_stub_actvity, mSessionFragment);
                transaction.commitAllowingStateLoss();
                //首页跑马灯停掉
                HomeFragment homeNewFragment = (HomeFragment)getFragment(TAB_HOME);
                if (homeNewFragment != null && homeNewFragment.text_marquee_hight != null){
                    homeNewFragment.text_marquee_hight.stopScroll();
                    homeNewFragment.showHomeAd(false);
                }
            }
        }, 300);

    }
    public void hideSessionFragment(){
        clearServiceMapData(Constants.ServicePageType.SESSIONFRAGMENT);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (mSessionFragment!=null) {
            transaction.remove(mSessionFragment);
            mSessionFragment = null;
        }
        transaction.commitAllowingStateLoss();

        //首页跑马灯状态更新
        HomeFragment homeNewFragment = (HomeFragment)getFragment(TAB_HOME);
        if (homeNewFragment != null){
            homeNewFragment.comeBackUpdateMarquee();
            homeNewFragment.showHomeAd(true);
        }
    }

    public Fragment getFragment(int fragmentId){
        Class<? extends Fragment> clz = getPrimaryFragmentClass(fragmentId);
        String mCurrentPrimaryFragmentTag = clz.getName();
        Fragment fragment = mFragmentManager
                .findFragmentByTag(mCurrentPrimaryFragmentTag);
        return fragment;
    }

    public void showActivityUI(String id) {
        addSessionFragment(id);
        mIsHome = false;
        mActivityLayout.setVisibility(View.VISIBLE);
        int bottomBarHeight = mBottomBar.getHeight();
        int width = mActivityLayout.getWidth();
        int maskHeight = mMaskLayout.getHeight() + bottomBarHeight;
        int CartHeight = mCartLayout.getHeight();
        ObjectAnimator animatorBar = animatorUtils.translateY(mBottomBar, 0, bottomBarHeight,
                halfCurrentAnimDuration, null);
        ObjectAnimator animatorMask = animatorUtils.translateY(mMaskLayout, 0, maskHeight,
                halfCurrentAnimDuration, null);
        ObjectAnimator animatorCart = animatorUtils.translateY(mCartLayout, 0, CartHeight,
                halfCurrentAnimDuration, null);

        ObjectAnimator animatorActivity = animatorUtils.translateX(mActivityLayout, width, 0,
                currentAnimDuration, null);

        animatorBar.addListener(new LayerEnableAnimatorListenerAdapter(mBottomBar) {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                ObjectAnimator animatorCartDetail = animatorUtils.translateY(mCartDetailLayout,
                        mCartDetailLayout.getHeight(), 0, halfCurrentAnimDuration, null);
                mCartDetailLayout.setVisibility(View.VISIBLE);
                mCartDetailView.setVisibility(View.VISIBLE); 
                mCartDetailViewHide.setVisibility(View.VISIBLE); 
                //                mCartDetailContent.setVisibility(View.VISIBLE);
                //                UiUtils.updateCartDescription(YMXMainActivity.this,Constants.PageType.SESSION);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(animatorCartDetail);
                set.start();

            }
        });
        AnimatorSet set = new AnimatorSet();
        set.playTogether(animatorBar, animatorMask, animatorCart,
                animatorActivity);
        set.start();
    }
    
    public void showActivityUINoAnimation(String id) {
        addSessionFragment(id);
        mIsHome = false;
        mActivityLayout.setVisibility(View.VISIBLE);
        int bottomBarHeight = mBottomBar.getHeight();
        int width = mActivityLayout.getWidth();
        int maskHeight = mMaskLayout.getHeight() + bottomBarHeight;
        int CartHeight = mCartLayout.getHeight();
        ObjectAnimator animatorBar = animatorUtils.translateY(mBottomBar, 0, bottomBarHeight,
                halfCurrentAnimDuration2, null);
        ObjectAnimator animatorMask = animatorUtils.translateY(mMaskLayout, 0, maskHeight,
                halfCurrentAnimDuration2, null);
        ObjectAnimator animatorCart = animatorUtils.translateY(mCartLayout, 0, CartHeight,
                halfCurrentAnimDuration2, null);

        ObjectAnimator animatorActivity = animatorUtils.translateX(mActivityLayout, width, 0,
                0, null);

        animatorBar.addListener(new LayerEnableAnimatorListenerAdapter(mBottomBar) {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                ObjectAnimator animatorCartDetail = animatorUtils.translateY(mCartDetailLayout,
                        mCartDetailLayout.getHeight(), 0, halfCurrentAnimDuration, null);
                mCartDetailLayout.setVisibility(View.VISIBLE);
                mCartDetailView.setVisibility(View.VISIBLE);
                mCartDetailViewHide.setVisibility(View.VISIBLE);
//                mCartDetailContent.setVisibility(View.VISIBLE);
//                UiUtils.updateCartDescription(YMXMainActivity.this,Constants.PageType.SESSION);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(animatorCartDetail);
                set.start();

            }
        });
        AnimatorSet set = new AnimatorSet();
        set.playTogether(animatorBar, animatorMask, animatorCart,
                animatorActivity);
        set.start();
    }

    public void hideActivityUI() {
        int width = mActivityLayout.getWidth();
        ObjectAnimator animatorActivity = animatorUtils.translateX(mActivityLayout, 0, width,
                currentAnimDuration, null);
        ObjectAnimator animatorCartDetail = animatorUtils.translateY(mCartDetailLayout, 0,
                mCartDetailLayout.getHeight(), halfCurrentAnimDuration, null);
        animatorActivity.addListener(new LayerEnableAnimatorListenerAdapter(mActivityLayout)
        {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                mIsBackAnimating = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mIsBackAnimating = false;
                mIsHome = true;
                hideSessionFragment();
                UiUtils.updateCartDescription(YMXMainActivity.this, Constants.PageType.HOME);
            }
        }
                );
        animatorCartDetail.addListener(new LayerEnableAnimatorListenerAdapter(mBottomBar) {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                int bottomBarHeight = mBottomBar.getHeight();
                int maskHeight = mMaskLayout.getHeight() + bottomBarHeight;
                int CartHeight = mCartLayout.getHeight();
                ObjectAnimator animatorBar = animatorUtils.translateY(mBottomBar, bottomBarHeight,
                        0, halfCurrentAnimDuration, null);
                ObjectAnimator animatorMask = animatorUtils.translateY(mMaskLayout, maskHeight, 0,
                        halfCurrentAnimDuration, null);
                ObjectAnimator animatorCart = animatorUtils.translateY(mCartLayout, CartHeight, 0,
                        halfCurrentAnimDuration, null);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(animatorBar, animatorMask, animatorCart);
                set.start();
                mCartDetailLayout.setVisibility(View.GONE);

            }
        });
        AnimatorSet set = new AnimatorSet();
        set.playTogether(animatorActivity, animatorCartDetail);
        set.start();
    }

    public void hideActivityUINoAnimation() {
        int width = mActivityLayout.getWidth();
        ObjectAnimator animatorActivity = animatorUtils.translateX(mActivityLayout, 0, width,
                0, null);
        ObjectAnimator animatorCartDetail = animatorUtils.translateY(mCartDetailLayout, 0,
                mCartDetailLayout.getHeight(), halfCurrentAnimDuration2, null);
        animatorActivity.addListener(new LayerEnableAnimatorListenerAdapter(mActivityLayout) {
                                         @Override
                                         public void onAnimationStart(Animator animation) {
                                             super.onAnimationStart(animation);
                                             mIsBackAnimating = true;
                                         }

                                         @Override
                                         public void onAnimationEnd(Animator animation) {
                                             super.onAnimationEnd(animation);
                                             mIsBackAnimating = false;
                                             mIsHome = true;
                                             hideSessionFragment();
                                             UiUtils.updateCartDescription(YMXMainActivity.this, Constants.PageType.HOME);
                                         }
                                     }
        );
        animatorCartDetail.addListener(new LayerEnableAnimatorListenerAdapter(mBottomBar) {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                int bottomBarHeight = mBottomBar.getHeight();
                int maskHeight = mMaskLayout.getHeight() + bottomBarHeight;
                int CartHeight = mCartLayout.getHeight();
                ObjectAnimator animatorBar = animatorUtils.translateY(mBottomBar, bottomBarHeight,
                        0, halfCurrentAnimDuration2, null);
                ObjectAnimator animatorMask = animatorUtils.translateY(mMaskLayout, maskHeight, 0,
                        halfCurrentAnimDuration2, null);
                ObjectAnimator animatorCart = animatorUtils.translateY(mCartLayout, CartHeight, 0,
                        halfCurrentAnimDuration2, null);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(animatorBar, animatorMask, animatorCart);
                set.start();
                mCartDetailLayout.setVisibility(View.GONE);
                showActivityUINoAnimation("");
            }
        });
        AnimatorSet set = new AnimatorSet();
        set.playTogether(animatorActivity, animatorCartDetail);
        set.start();
    }

    public void setCityName(String cityName){
        mCityName=cityName;        
    }

    public ImageView getmCartView() {
        return mCartView;
    }

    public ImageView getmCartDetailViewHide() {
        return mCartDetailViewHide;
    }

}
